package es.usc.citius.servando.calendula.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import es.usc.citius.servando.calendula.HomePagerActivity;
import es.usc.citius.servando.calendula.pinlock.PINManager;
import es.usc.citius.servando.calendula.pinlock.PinLockActivity;
import es.usc.citius.servando.calendula.pinlock.UnlockStateManager;

public class StartActivity extends Activity {
    public static final String EXTRA_RETURN_TO_PREVIOUS = "StartActivity.extras.return_to_previous";

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        verifyUnlockAndLaunch();
    }

    private void verifyUnlockAndLaunch() {
        if (PINManager.isPINSet() && !UnlockStateManager.getInstance().isUnlocked()) {
            Intent i = new Intent(this, PinLockActivity.class);
            i.setAction(PinLockActivity.ACTION_VERIFY_PIN);
            startActivityForResult(i, PinLockActivity.REQUEST_VERIFY);
        } else {
            boolean returnToPrevious = getIntent().getBooleanExtra(EXTRA_RETURN_TO_PREVIOUS, false);
            if (!returnToPrevious) {
                // if "return to previous" is specified, just finish this activity to go back in the stack
                startActivity(new Intent(this, HomePagerActivity.class));
            }
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PinLockActivity.REQUEST_VERIFY) {
            if (resultCode == Activity.RESULT_CANCELED) {
                finish();
            } else {
                verifyUnlockAndLaunch();
            }
        }
    }
}
